package com.bite.forum.controller;

import com.bite.forum.common.AppConfig;
import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.User;
import com.bite.forum.service.impl.UserServiceImpl;
import com.bite.forum.utils.MD5Util;
import com.bite.forum.utils.StringUtil;
import com.bite.forum.utils.UUIDUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping("/register")
    public AppResult register(@RequestParam(value = "username") @NonNull String username ,
                              @RequestParam(value = "nickname") @NonNull String nickname ,
                              @RequestParam(value = "password") @NonNull String password ,
                              @RequestParam(value = "passwordRepeat") @NonNull String passwordRepeat){

        /*if(StringUtil.isEmpty(username)
           ||StringUtil.isEmpty(nickname)
           ||StringUtil.isEmpty(password)
           ||StringUtil.isEmpty(passwordRepeat)){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }
*/
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());

            throw new ApplicationException(ResultCode.FAILED_TWO_PWD_NOT_SAME.getMessage());
        }

        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password , salt);
        user.setSalt(salt);
        user.setPassword(encryptPassword);

        userService.createNormalUser(user);

        return AppResult.success();
    }

    @RequestMapping("/login")
    public AppResult login(HttpServletRequest request ,
                           @RequestParam("username") @NonNull String username ,
                           @RequestParam("password") @NonNull String password){

        User user = userService.login(username , password);

        if(user == null){
            log.info("2");
            //参数校验
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(ResultCode.FAILED_USER_EXISTS.getMessage());
        }

        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION , user);

        return AppResult.success();
    }

    @GetMapping("/info")
    public AppResult info(HttpServletRequest request ,
                          @RequestParam(value = "id" , required = false) Long id){
        User user = null;
        //校验id是否为空
        if(id == null){
            HttpSession session = request.getSession();
            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
                return AppResult.failed(ResultCode.FAILED_NOLOGIN);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }
        else {
            user = userService.selectByPrimaryKey(id);
        }
        if(user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        //判断session是否登入
        if(session == null){
            log.warn("用户未登入");
            throw new ApplicationException(ResultCode.FAILED_NOLOGIN.getMessage());
        }

        session.invalidate();
        return AppResult.success("退出成功");
    }
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request ,
                                @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark){
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        userService.modifyInfo(updateUser);

        user = userService.selectByPrimaryKey(user.getId());
        session.setAttribute(AppConfig.USER_SESSION , user);
        return AppResult.success(user);
    }
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request ,
                                    @RequestParam("newPassword") @NonNull String newPassword ,
                                    @RequestParam("oldPassword") @NonNull String oldPassword ,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(!newPassword.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME));
        }

        userService.modifyPassword(user.getId(), newPassword , oldPassword);

        if(session != null){
            session.invalidate();
        }
        return AppResult.success();
    }
}



















